/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Damaged;
import com.jeeplus.modules.ap.service.DamagedService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.Dispatching;
import com.jeeplus.modules.tms.service.DispatchingService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.Fine;
import com.jeeplus.modules.ap.service.FineService;

/**
 * 罚款Controller
 * @author 李超辉
 * @version 2018-12-18
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/fine")
public class FineController extends BaseController {

	@Autowired
	private FineService fineService;
	@Autowired
	private DamagedService damagedService;
	@Autowired
	private DispatchingService dispatchingService;
	
	@ModelAttribute
	public Fine get(@RequestParam(required=false) String id) {
		Fine entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = fineService.get(id);
		}
		if (entity == null){
			entity = new Fine();
		}
		return entity;
	}
	
	/**
	 * 罚款列表页面
	 */
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/fineList";
	}
	/**
	 * 罚款列表页面(甲方)
	 */
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/ap/1/fineList";
	}
	/**
	 * 罚款列表页面(内部)
	 */
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/ap/2/fineList";
	}
	/**
	 * 罚款列表页面（外包）
	 */
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/ap/3/fineList";
	}
	/**
	 * 罚款列表页面（明细）
	 */
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/ap/4/fineList";
	}
	/**
	 * 罚款列表页面（统计）
	 */
	@RequestMapping(value = {"list5"})
	public String list5() {
		return "modules/ap/5/fineList";
	}
	
		/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
		Page<Fine> page = fineService.findPage(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}

	/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
		fine.setRemarks("已确认");
		fine.setJf(1);
		Page<Fine> page = fineService.findPage(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}
	/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
		fine.setRemarks("已确认");
		fine.setNb(1);
		Page<Fine> page = fineService.findPage(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}
	/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
		fine.setRemarks("已确认");
		fine.setWb(1);
		Page<Fine> page = fineService.findPage(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}
	/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
		fine.setRemarks("已确认");
		Page<Fine> page = fineService.findPage(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}
	/**
	 * 罚款列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:list")
	@RequestMapping(value = "data5")
	public Map<String, Object> data5(Fine fine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Fine> page = fineService.findPage1(new Page<Fine>(request, response), fine);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑罚款表单页面
	 */
	@RequiresPermissions(value={"ap:fine:view","ap:fine:add","ap:fine:edit"},logical=Logical.OR)
	@RequestMapping(value = "ck")
	public String form(String code, Model model) {
		Fine fine=fineService.findUniqueByProperty("code",code);
		fine=fineService.get(fine.getId());
		model.addAttribute("fine", fine);
		return "modules/ap/fineForm";
	}

	/**
	 * 查看，增加，编辑罚款表单页面
	 */
	@RequiresPermissions(value={"ap:fine:view","ap:fine:add","ap:fine:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Fine fine, Model model) {
		if(fine.getIsNewRecord()){
		String pro= UserUtils.getUseroffice();
		fine.setBsc(UserUtils.getbsc());
		if(!pro.equals("总部")){
			fine.setPro(pro);
		}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Fine p=new Fine();
			p.setCode(code);
			List<Fine> l=fineService.findList(p);
			if(l==null||l.size()<1){
				fine.setCode(code+"001"+"WBKH");
			}else{
				if(l.size()/10==0){
					fine.setCode(code+"00"+(l.size()+1)+"WBKH");
				}else
				if(l.size()/100==0){
					fine.setCode(code+"0"+(l.size()+1)+"WBKH");
				}else{fine.setCode(code+(l.size()+1)+"WBKH");}

			}
		}
		model.addAttribute("fine", fine);
		return "modules/ap/fineForm";
	}

	/**
	 * 保存罚款
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:fine:add","ap:fine:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Fine fine, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, fine)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		String yd=fine.getWbglydh();
		String hs=fine.getHs();
		Dispatching d=dispatchingService.findUniqueByProperty("hth",yd);
		Damaged dm=damagedService.findUniqueByProperty("code",hs);
		if(d==null||d.getId().equals("")){
			j.setSuccess(false);
			j.setMsg("请检查合同号");
			return j;
		}
		if(dm==null||dm.getId().equals("")){
			j.setSuccess(false);
			j.setMsg("请检查货损单号");
			return j;
		}
		fine.setRemarks("已创建");
		fine.setNb(0);
		fine.setWb(0);
		fine.setJf(0);
		fineService.save(fine);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存罚款成功");
		return j;
	}
	
	/**
	 * 删除罚款
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Fine fine, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		fineService.delete(fine);
		j.setMsg("删除罚款成功");
		return j;
	}
	
	/**
	 * 批量删除罚款
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Fine fine, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		fine.setRemarks("已确认");
		if(fine.getZxje()!=null&&!fine.getZxje().equals("")&&!fine.getZxje().equals("0")){
			fine.setJf(1);
		}
		if(fine.getNbzxje()!=null&&!fine.getNbzxje().equals("")&&!fine.getNbzxje().equals("0")){
			fine.setNb(1);
		}
		if(fine.getWbzxje()!=null&&!fine.getWbzxje().equals("")&&!fine.getWbzxje().equals("0")){
			fine.setWb(1);
		}
		fineService.save(fine);
		j.setMsg("确认成功");
		return j;
	}


	/**
	 * 批量删除罚款
	 */
	@ResponseBody
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			fineService.delete(fineService.get(id));
		}
		j.setMsg("删除罚款成功");
		return j;
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:fine:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Fine fine, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "罚款"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Fine> page = fineService.findPage(new Page<Fine>(request, response, -1), fine);
    		new ExportExcel("罚款", Fine.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出罚款记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:fine:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Fine> list = ei.getDataList(Fine.class);
			for (Fine fine : list){
				try{
					fineService.save(fine);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条罚款记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条罚款记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入罚款失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/fine/?repage";
    }
	
	/**
	 * 下载导入罚款数据模板
	 */
	@RequiresPermissions("ap:fine:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "罚款数据导入模板.xlsx";
    		List<Fine> list = Lists.newArrayList(); 
    		new ExportExcel("罚款数据", Fine.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/fine/?repage";
    }

}